package org.gap.jseed.util;

import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;

import javassist.CtClass;

public class ClassHierarchyExtractor {
	
	public static Collection<CtClass> extract(CtClass type) {
		LinkedList<CtClass> result = new LinkedList<CtClass>();
		
		Collection<CtClass> extendedClasses = getExtendedClasses(type);
		extendedClasses.add(type);
		
		for (CtClass eachAbstract : extendedClasses) {
			result.add(eachAbstract);
			Collections.addAll(result, getInterfacesFor(eachAbstract));
		}
		
		return result;
	}

	private static CtClass[] getInterfacesFor(CtClass implementingClass) {
		if (ClassUtil.hasInterfaces(implementingClass)) {
			return ClassUtil.getInterfaces(implementingClass);
		}
		return new CtClass[]{};
	}

	private static Collection<CtClass> getExtendedClasses(CtClass current) {
		LinkedList<CtClass> result = new LinkedList<CtClass>();
		
		while (ClassUtil.hasAbstractClass(current)) {
			current = ClassUtil.getSuperClass(current);
			result.add(current);
		}
		
		return result;
	}
}
